//
//  UIImageExtension.swift
//  ShareVipForBusiness
//
//  Created by OzIntel on 2017/10/11.
//  Copyright © 2017年 zev. All rights reserved.
//

import UIKit

import UIKit



extension UIImage{
    /**
     使用颜色实例化图片，大小为1像素

     - parameter color: 颜色

     - returns: 图片
     */
    public convenience init?(color: UIColor) {
        self.init(color: color, rect: CGRect(x: 0, y: 0, width: 1, height: 1))
    }

    //MARK: - 创建图片
    /**
     使用颜色实例化图片

     - parameter color: 颜色值
     - parameter rect:  图片大小

     - returns: 图片
     */
    public convenience init?(color: UIColor, rect: CGRect) {

        UIGraphicsBeginImageContext(rect.size);
        let context = UIGraphicsGetCurrentContext();

        context?.setFillColor(color.cgColor);
        context?.fill(rect);

        let image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext()
        guard let data = image!.jpegData(compressionQuality: 1.0) else {self.init(); return}
        self.init(data: data)
    }
    
    class func image(color:UIColor) -> UIImage {
        return UIImage.image(color: color, size: CGSize(width: 1, height: 1))
    }
    
    /// 根据颜色创建图片
    ///
    /// - Parameters:
    ///   - color: 颜色
    ///   - size: 图片尺寸
    /// - Returns: 颜色图片
    class func image(color:UIColor,size:CGSize) -> UIImage {
        UIGraphicsBeginImageContext(size)
        let context : CGContext = UIGraphicsGetCurrentContext()!
        context.setFillColor(color.cgColor)
        context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    /// 缩放图片尺寸
    ///
    /// - Parameters:
    ///   - image: 原图片
    ///   - size: 缩放比例
    /// - Returns: 缩放后的图片
    class func scaleImageToSize(image:UIImage, size:CGSize) -> UIImage {
        UIGraphicsBeginImageContext(image.size)
        image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    class func scaleImageToWidth(image:UIImage, width:CGFloat) -> UIImage {
        let height = image.size.height * width/image.size.width;
        let size = CGSize(width: width, height: height)
        return UIImage.scaleImageToSize(image: image, size: size)
    }
    class func scaleImageToHeight(image:UIImage, height:CGFloat) -> UIImage {
        let width = image.size.width * height/image.size.height;
        let size = CGSize(width: width, height: height)
        return UIImage.scaleImageToSize(image: image, size: size)
    }
    
    /// 裁剪图片
    ///
    /// - Parameters:
    ///   - image: 图片
    ///   - inRect: 裁剪范围
    /// - Returns: 裁剪后的图片
    class func cropping(image:UIImage, inRect:CGRect) -> UIImage {
        let sourceImageRef = image.cgImage
        
        //按照给定的矩形区域进行剪裁
        let newImageRef = sourceImageRef!.cropping(to: inRect);
        
        //将CGImageRef转换成UIImage
        let newImage = UIImage(cgImage: newImageRef!)
        
        //返回剪裁后的图片
        return newImage;
    }
    
    class func save(image:UIImage, name:String) {
        let data : Data = image.pngData()!
        let path : NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
        let filePath = path.appendingPathComponent(name)
        let url = URL(fileURLWithPath: filePath)
        
        try? data.write(to: url)
    }
    class func getLocalImage(name:String) -> UIImage {
        let  path = "\(NSHomeDirectory())/Documents/\(name).png"
        return UIImage(contentsOfFile: path)!
    }
    
    
    /// 图片添加水印
    ///
    /// - Parameters:
    ///   - waterImage: 水印图片
    ///   - waterRect: 水印图片frame
    ///   - image: 原图片
    ///   - imageRect: 原图片frame
    /// - Returns: 合成的图片
    class func addWaterMarkImage(waterImage:UIImage, waterRect:CGRect, image:UIImage,imageRect:CGRect) -> UIImage {
        // 创建一个graphics context来画我们的东西
        UIGraphicsBeginImageContext(image.size);
        // graphics context就像一张能让我们画上任何东西的纸。我们要做的第一件事就是把person画上去
        image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
        // 然后在把hat画在合适的位置
        waterImage.draw(in: CGRect(x: waterRect.origin.x, y: waterRect.origin.y, width: waterRect.size.width, height: waterRect.size.height))
        // 通过下面的语句创建新的UIImage
        let newImage = UIGraphicsGetImageFromCurrentImageContext();
        // 最后，我们必须得清理并关闭这个再也不需要的context
        UIGraphicsEndImageContext();
        return newImage!;
    }
    
    
    class func createQRImage(QRString: String?) -> UIImage?{
        guard var QRString = QRString  else {
            return nil
        }
        
        // 1、判断用户传过来的base64的字符串是否是以data开口的，如果是以data开头的，那么就获取字符串中的base代码，然后在转换，如果不是以data开头的，那么就直接转换
        
        if (QRString.hasPrefix("data:image")) {
            
            guard let newBase64String = QRString.components(separatedBy: ",").last else {
                return nil
            }
            QRString = newBase64String
        }
        // 2、将处理好的base64String代码转换成NSData
        guard let imgNSData = NSData(base64Encoded: QRString, options: NSData.Base64DecodingOptions()) else {
            return nil
        }
        // 3、将NSData的图片，转换成UIImage
        guard let codeImage = UIImage(data: imgNSData as Data) else {
            return nil
        }
        return codeImage
    }
    
    
    /**
     *  压缩上传图片到指定字节
     *
     *  image     压缩的图片
     *  maxLength 压缩后最大字节大小
     *
     *  return 压缩后图片的二进制
     */
    func compressImage(image: UIImage, maxLength: Int) -> Data? {
        
        let newSize = self.scaleImage(image: image, imageLength: 1000)
        let newImage = self.resizeImage(image: image, newSize: newSize)
        
        var compress:CGFloat = 0.9
        var data = newImage.jpegData(compressionQuality: compress)
        
        while (data?.count)! > maxLength && compress > 0.01 {
            compress -= 0.02
            data = newImage.jpegData(compressionQuality: compress)
        }
        
        return data
    }
    
    
    /**
     *  通过指定图片最长边，获得等比例的图片size
     *
     *  image       原始图片
     *  imageLength 图片允许的最长宽度（高度）
     *
     *  return 获得等比例的size
     */
    func  scaleImage(image: UIImage, imageLength: CGFloat) -> CGSize {
        
        var newWidth:CGFloat = image.size.width
        var newHeight:CGFloat = image.size.height
        let width = image.size.width
        let height = image.size.height
        
        if (width > imageLength || height > imageLength){
            
            if (width > height) {
                
                newWidth = imageLength;
                newHeight = newWidth * height / width;
                
            }else if(height > width){
                
                newHeight = imageLength;
                newWidth = newHeight * width / height;
                
            }else{
                
                newWidth = imageLength;
                newHeight = imageLength;
            }
            
        }
        return CGSize(width: newWidth, height: newHeight)
    }
    
    /**
     *  获得指定size的图片
     *
     *  image   原始图片
     *  newSize 指定的size
     *
     *  return 调整后的图片
     */
    func resizeImage(image: UIImage, newSize: CGSize) -> UIImage {
        UIGraphicsBeginImageContext(newSize)
        image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage!
    }
    
    class func blurryImage(image:UIImage, blur:CGFloat) -> UIImage {
        let inputImage = CIImage.init(cgImage: image.cgImage!)
        let filter = CIFilter.init(name: "CIGaussianBlur", parameters: [kCIInputImageKey:inputImage,"inputRadius":blur])
        let outputImage = filter?.outputImage
        let context = CIContext.init(options: nil)
        let outImage = context.createCGImage(outputImage!, from: inputImage.extent)
        return UIImage.init(cgImage: outImage!)
    }
    
    
    //    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"
    //    keysAndValues:kCIInputImageKey, inputImage,
    //    @"inputRadius", @(blur), nil, nil];
    
    class func screenImage(size:CGSize) -> UIImage{
        UIGraphicsBeginImageContext(size)
        let context = UIGraphicsGetCurrentContext()
        UIApplication.shared.keyWindow?.layer.render(in: context!)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }
    
    
}

